﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace LWH.XmlHandler
{
    /// <summary>
    /// 从父节点中尝试解析自己，如果父节点中存在自己定义的节点，则调用DidGetElement进行处理
    /// </summary>
    public abstract class AbstractElementHandler
    {
        /// <summary>
        /// 元素名，其本质是用于从父节点解析当前节点的XPath
        /// </summary>
        string mElementName;

        public AbstractElementHandler(string elementName)
        {
            mElementName = elementName;
        }

        public bool handleXml(Dictionary<string, object> context)
        {
            var isHandle = false;
            var parentElement = (XmlNode)context["ParentElement"];

            var curElementList = getCurrentElementInParentList(parentElement);

            foreach(XmlNode element in curElementList)
            {
                DidGetElement(context, element);
                isHandle = true;
            }

            return isHandle;
        }

        /**
         * 解析出元素
         * @param context 上下午
         * @param currentElement 解析出的元素
         */
        protected abstract void DidGetElement(Dictionary<string, object> context, XmlNode currentElement);


        public string getElementName()
        {
            return mElementName;
        }

        XmlNodeList getCurrentElementInParentList(XmlNode parentElement)
        {
            return parentElement.SelectNodes(getElementName());
        }

        XmlNode getCurrentElementInParent(XmlNode parentElement)
        {
            return parentElement.SelectSingleNode(getElementName());
        }

    }
}
